﻿using SC;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;

public class SCClient{

    private SocketClient socketClient;
    public delegate  void SCRecvEvent(Socket socketSend, SC.MessageType messageType, byte[] objBuf);
    public SCRecvEvent scRecvEvent;

    public SCClient() {
        socketClient = new SocketClient();
        socketClient.recvEvent += SCRecv;
        socketClient.connectError += ((e) =>
        {
            Console.WriteLine(e);
        });
    }

    public void Connect(string ip,int port)
    {
        try
        {
            socketClient.ConnectServer(ip, port);
        }catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        
    }

    private void OnDispose()
    {
        socketClient.Close();
    }

    //发送序列化对象
    public void Send<T>(MessageType messageType,T value)
    {
        byte[] encodedaata = SC.MessagePack.SerializeObject(messageType, value);
        socketClient.Send(encodedaata);
    }

    /// <summary>
    /// 发送字节流
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="messageType"></param>
    /// <param name="stream"></param>
    public void SendStream<T>(MessageType messageType, byte[] stream)
    {
        byte[] encodedaata = SC.MessagePack.SerializeByteStream(messageType, stream);
        socketClient.Send(encodedaata);
    }

    /// <summary>
    /// 客户端接收消息处理
    /// </summary>
    /// <param name="socket"></param>
    public void SCRecv(Socket socket)
    {
        byte[] msgType, objBuf;
        SC.MessagePack.DeserializeBuf(socket, out msgType, out objBuf);
        MessageType messageType = (MessageType)BitConverter.ToInt32(msgType, 0);
        if (scRecvEvent != null)
        {
            scRecvEvent(socket, messageType, objBuf);
        }
    }

}
